<template>
  <div class="app-config-list">
    <div class="list-header">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>添加配置
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索配置名称"
        clearable
        class="search-input"
        @input="handleSearchInput"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredConfigs"
      stripe
      style="width: 100%"
      :empty-text="loading ? '加载中...' : '暂无配置数据'"
    >
      <el-table-column prop="name" label="名称" min-width="150">
        <template #default="{ row }">
          <div class="config-name">
            <span>{{ row.name }}</span>
            <el-tag v-if="row.isDefault" size="small" type="success">默认</el-tag>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="description" label="描述" min-width="200">
        <template #default="{ row }">
          <el-tooltip
            v-if="row.description && row.description.length > 50"
            :content="row.description"
            placement="top"
            effect="light"
          >
            <span>{{ row.description.substring(0, 50) }}...</span>
          </el-tooltip>
          <span v-else>{{ row.description || '无描述' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="aiModelConfig" label="AI模型" width="180">
        <template #default="{ row }">
          <el-tooltip
            :content="row.aiModelConfig ? `${row.aiModelConfig.name} (${row.aiModelConfig.type})` : '使用默认AI模型'"
            placement="top"
          >
            <div class="ai-model-info">
              <span>{{ row.aiModelConfig ? row.aiModelConfig.name : '默认AI模型' }}</span>
              <el-tag v-if="row.aiModelConfig?.isDefault" size="small" type="info">默认</el-tag>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      
      <el-table-column prop="updatedAt" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.updatedAt) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="isEnabled" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.isEnabled"
            :disabled="row.isDefault"
            @change="(val: boolean) => handleStatusChange(row.id, val)"
          />
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="primary" 
              :disabled="row.isDefault"
              @click="handleSetDefault(row.id)"
            >
              设为默认
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              :disabled="row.isDefault"
              @click="handleDelete(row.id, row.name)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑应用配置' : '创建应用配置'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名称" />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择配置类型" style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选择器" prop="selector">
          <el-input v-model="form.selector" placeholder="请输入DOM选择器（可选）" />
        </el-form-item>
        
        <el-form-item label="系统消息" prop="messages">
          <el-card class="messages-card" shadow="never">
            <template #header>
              <div class="messages-header">
                <span>角色消息列表</span>
                <el-button type="primary" link @click="addMessage">添加消息</el-button>
              </div>
            </template>
            
            <div v-for="(msg, index) in form.messages" :key="index" class="message-item">
              <div class="message-header">
                <el-select v-model="msg.role" placeholder="角色" style="width: 120px">
                  <el-option label="系统" value="system" />
                  <el-option label="用户" value="user" />
                  <el-option label="助手" value="assistant" />
                </el-select>
                <el-button type="danger" link @click="removeMessage(index)">删除</el-button>
              </div>
              <el-input
                v-model="msg.content"
                type="textarea"
                :rows="3"
                placeholder="请输入消息内容"
              />
            </div>
            
            <div v-if="form.messages.length === 0" class="no-messages">
              <el-empty description="暂无消息" />
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="额外配置" prop="extraConfig">
          <el-input
            v-model="extraConfigJson"
            type="textarea"
            :rows="5"
            placeholder="请输入JSON格式的额外配置（可选）"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入配置描述（可选）"
          />
        </el-form-item>
        
        <el-form-item label="启用状态" prop="isEnabled">
          <el-switch v-model="form.isEnabled" />
        </el-form-item>
        
        <el-form-item label="默认配置" prop="isDefault">
          <el-switch v-model="form.isDefault" />
        </el-form-item>

        <el-form-item label="AI模型配置" prop="aiModelConfigId">
          <el-select 
            v-model="form.aiModelConfigId" 
            placeholder="选择AI模型配置（可选）" 
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in aiModelConfigs"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.name }}</span>
                <el-tag size="small" :type="item.isDefault ? 'success' : 'info'">
                  {{ item.type }}{{ item.isDefault ? ' (默认)' : '' }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">
            不选择时将使用系统默认的AI模型配置
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue';
import { useAppConfigStore } from '../store/appConfig';
import { AppType } from '../api/appConfig';
import { useAIModelStore } from '../store/aiModel';
import { debounce } from '../utils/common';

const appConfigStore = useAppConfigStore();
const aiModelStore = useAIModelStore();
const loading = computed(() => appConfigStore.loading);
const submitting = computed(() => appConfigStore.submitting);
const aiModelConfigs = computed(() => aiModelStore.configList);

// 表格数据
const searchQuery = ref('');
const configs = computed(() => appConfigStore.configList);
const filteredConfigs = computed(() => {
  if (!searchQuery.value) return configs.value;
  return configs.value.filter(config => 
    config.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 搜索输入防抖处理（由于是前端过滤，这里只是占位，实际不需要调用API）
const handleSearchInput = debounce(() => {
  // 前端过滤，无需额外处理
}, 300);

// 表单相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();
const form = ref({
  id: '',
  name: '',
  type: AppType.BROWSER_EXTENSION,
  selector: '',
  messages: [] as { role: string; content: string }[],
  extraConfig: {},
  description: '',
  isEnabled: true,
  isDefault: false,
  aiModelConfigId: null as number | null
});

const extraConfigJson = ref('{}');
watch(extraConfigJson, (newVal) => {
  try {
    form.value.extraConfig = JSON.parse(newVal);
  } catch (e) {
    // 解析错误时不更新extraConfig
  }
});

// 类型选项
const typeOptions = [
  { label: '浏览器插件', value: AppType.BROWSER_EXTENSION },
  { label: 'Web应用', value: AppType.WEB_APP },
  { label: '移动应用', value: AppType.MOBILE_APP },
  { label: '脚本', value: AppType.SCRIPT },
  { label: '其他', value: AppType.OTHER }
];

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择配置类型', trigger: 'change' }
  ]
};

// 初始化
onMounted(async () => {
  await appConfigStore.fetchConfigList();
  await aiModelStore.fetchConfigList();
});

// 获取类型标签样式
const getTypeTagType = (type: AppType) => {
  const typeMap = {
    [AppType.BROWSER_EXTENSION]: 'primary',
    [AppType.WEB_APP]: 'success',
    [AppType.MOBILE_APP]: 'warning',
    [AppType.SCRIPT]: 'info',
    [AppType.OTHER]: 'danger'
  };
  return typeMap[type] || 'info';
};

// 获取类型显示文本
const getTypeLabel = (type: AppType) => {
  const typeMap = {
    [AppType.BROWSER_EXTENSION]: '浏览器插件',
    [AppType.WEB_APP]: 'Web应用',
    [AppType.MOBILE_APP]: '移动应用',
    [AppType.SCRIPT]: '脚本',
    [AppType.OTHER]: '其他'
  };
  return typeMap[type] || '未知';
};

// 格式化日期
const formatDate = (dateStr: string | Date) => {
  if (!dateStr) return '未知';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 添加消息
const addMessage = () => {
  form.value.messages.push({ role: 'system', content: '' });
};

// 移除消息
const removeMessage = (index: number) => {
  form.value.messages.splice(index, 1);
};

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false;
  form.value = {
    id: '',
    name: '',
    type: AppType.BROWSER_EXTENSION,
    selector: '',
    messages: [],
    extraConfig: {},
    description: '',
    isEnabled: true,
    isDefault: false,
    aiModelConfigId: null
  };
  extraConfigJson.value = '{}';
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  form.value = { ...row };
  extraConfigJson.value = JSON.stringify(row.extraConfig || {}, null, 2);
  dialogVisible.value = true;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    
    try {
      // 尝试解析额外配置
      try {
        form.value.extraConfig = JSON.parse(extraConfigJson.value);
      } catch (e) {
        ElMessage.error('额外配置JSON格式错误');
        return;
      }
      
      if (isEdit.value) {
        await appConfigStore.updateConfig(form.value.id, form.value);
      } else {
        await appConfigStore.createConfig(form.value);
      }
      
      dialogVisible.value = false;
    } catch (error) {
      console.error('保存配置失败:', error);
    }
  });
};

// 处理删除
const handleDelete = (id: string | number, name: string) => {
  ElMessageBox.confirm(
    `确定要删除配置 "${name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await appConfigStore.deleteConfig(id);
    } catch (error) {
      console.error('删除配置失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理设置默认
const handleSetDefault = async (id: string | number) => {
  try {
    await appConfigStore.setDefaultConfig(id);
  } catch (error) {
    console.error('设置默认配置失败:', error);
  }
};

// 处理状态变更
const handleStatusChange = async (id: string | number, isEnabled: boolean) => {
  try {
    await appConfigStore.changeConfigStatus(id, isEnabled);
  } catch (error) {
    console.error('修改配置状态失败:', error);
  }
};
</script>

<style scoped>
.app-config-list {
  padding: 20px 0;
}

.list-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.config-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.messages-card {
  margin-bottom: 10px;
}

.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.no-messages {
  padding: 20px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.ai-model-info {
  display: flex;
  align-items: center;
  gap: 5px;
}
</style> 